package org.csu.jpetmanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.servlet.http.HttpSession;
import org.csu.jpetmanage.mapper.OrdersMapper;
import org.csu.jpetmanage.model.Item;
import org.csu.jpetmanage.model.Order;
import org.csu.jpetmanage.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;

import java.math.BigDecimal;
import java.net.http.HttpRequest;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;

@Controller
public class OrderController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private Order order;

    @Autowired
    private OrdersMapper ordersMapper;

    @GetMapping("/orderIndex")
    public String orderIndex(Model model){
        List<Order> orderList = ordersMapper.selectList(null);//查询所有的list记录
        model.addAttribute("orderList",orderList);
        return "orderManage/orderIndex";
    }

    @RequestMapping("/orderAdd")
    public String orderAdd(
            @RequestParam("username") String username,
            @RequestParam("shipAddress1") String shipAddress1,
            @RequestParam("shipAddress2") String shipAddress2,
            @RequestParam("shipCity") String shipCity,
            @RequestParam("shipZip") String shipZip,
            @RequestParam("shipCountry") String shipCountry,
            @RequestParam("billAddr") String billAddr,
            @RequestParam("billCity") String billCity,
            @RequestParam("totalPrice") String totalPrice,
            @RequestParam("creditCard") String creditCard,
            @RequestParam("cardType") String cardType,
            Model model, HttpSession session){
        order.setUsername(username);
        order.setShipAddress1(shipAddress1);
        order.setShipAddress2(shipAddress2);
        order.setShipCity(shipCity);
        order.setShipZip(shipZip);
        order.setShipCountry(shipCountry);
        order.setBillAddress1(billAddr);
        order.setBillCity(billCity);
        order.setTotalPrice(BigDecimal.valueOf(Integer.valueOf(totalPrice)));
        order.setCreditCard(creditCard);
        order.setCardType(cardType);
        /**
         * Id虽然是自增的，但是插入的时候Id却变成了0
         * 所以这里我们必须得写一个逻辑：
         * Id的值要设为当前表中最大的值+1**/
        //先获取当前表中最大的值
        List<Order> orderList = ordersMapper.selectList(null);//查询所有的list记录
        int max=0;
        for(int i=0;i<orderList.size();i++){
            if (max<orderList.get(i).getOrderId()){
                max=orderList.get(i).getOrderId();
            }
        }
        max++;
        order.setOrderId(max);
        /**
         * 时间也需要自己插入**/
        order.setOrderDate(new Date(System.currentTimeMillis()));
        /**
         * 把其他的属性也插入值进去吧
         */
        order.setShipState("无");
        order.setBillAddress2("无");
        order.setBillstate("无");
        order.setBillZip("无");
        order.setBillCountry("无");
        order.setCourier("无");
        order.setBillToFirstName("无");
        order.setBillToLastName("无");
        order.setShipToFirstName("无");
        order.setShipToLastName("无");
        order.setExpiryDate("无");
        order.setLocale("无");
        ordersMapper.insert(order);
        session.setAttribute("msg","插入成功");
        return "redirect:/orderIndex";
    }

    @RequestMapping("/orderDelete")
    public String orderDelete(
            @RequestParam("orderid") int orderid,
            HttpSession session
    ){
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("orderid",orderid);
        int sum = ordersMapper.deleteByMap(hashMap);
        System.out.println("sum is :"+sum);
        if (sum>=1){
            session.setAttribute("msg","删除成功");
        }
        return "redirect:/orderIndex";
    }

    @GetMapping("/orderEditAjax")
    @ResponseBody
    public Map<String,Object> orderEditAjax(
            @RequestParam("orderid") int orderid,
            HttpSession session
    ){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        /**
         * 其中第一个参数 "name" 就表示要比较的属性名称，而不是数据库中的列名。
         */
        queryWrapper.eq("orderId",orderid);//是根据Order实体类中的属性来进行取值,还是数据库的属性名？？？
        List<Order> orderList = ordersMapper.selectList(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        if (orderList.size()==1){
            System.out.println("orderList size is 1");
            order = orderList.get(0);
            session.setAttribute("editOrder",order);//待会处理编辑数据的时候需要用
            //把下面补全
            map.put("username",order.getUsername());
            map.put("shipAddress1",order.getShipAddress1());
            map.put("shipAddress2",order.getShipAddress2());
            map.put("shipCity",order.getShipCity());
            map.put("shipZip",order.getShipZip());
            map.put("shipCountry",order.getShipCountry());
            map.put("billAddr",order.getBillAddress1());
            map.put("billCity",order.getShipCountry());
            map.put("totalPrice",order.getTotalPrice());
            map.put("creditCard",order.getCreditCard());
            map.put("cardType",order.getCardType());
            return map;
        }
        return map;
    }

    @RequestMapping("/orderEdit")
    public String orderEdit(
            @RequestParam("editusername") String username,
            @RequestParam("editshipAddress1") String shipAddress1,
            @RequestParam("editshipAddress2") String shipAddress2,
            @RequestParam("editshipCity") String shipCity,
            @RequestParam("editshipZip") String shipZip,
            @RequestParam("editshipCountry") String shipCountry,
            @RequestParam("editbillAddr") String billAddr,
            @RequestParam("editbillCity") String billCity,
            @RequestParam("edittotalPrice") String totalPrice,
            @RequestParam("editcreditCard") String creditCard,
            @RequestParam("editcardType") String cardType,
            Model model, HttpSession session
    ){
        order = (Order)session.getAttribute("editOrder");
        order.setUsername(username);
        order.setShipAddress1(shipAddress1);
        order.setShipAddress2(shipAddress2);
        order.setShipCity(shipCity);
        order.setShipZip(shipZip);
        order.setShipCountry(shipCountry);
        order.setBillAddress1(billAddr);
        order.setBillCity(billCity);
        order.setTotalPrice(BigDecimal.valueOf(Integer.valueOf(totalPrice)));
        order.setCreditCard(creditCard);
        order.setCardType(cardType);
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("orderId",order.getOrderId());
        int rows = ordersMapper.update(order,updateWrapper);
        System.out.println("Edited rows number is: "+rows);
        session.setAttribute("msg","修改成功");
        return "redirect:/orderIndex";
    }

    @RequestMapping("/sendOutButton")
    public String sendOutButton(
            @RequestParam("orderid") int orderid,
            HttpSession session,
            Model model
    ){
        //通过orderid去查找order
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId",orderid);//是根据Order实体类中的属性来进行取值
        List<Order> orderList = ordersMapper.selectList(queryWrapper);
        order = orderList.get(0);//只有一条order
        /**
         * 需要判断order此时的付款状态，如果是未付款的话，那么是不允许发货的
         */
        if (order.getState().equals("未付款")){
            model.addAttribute("messageTitle", "提示");
            model.addAttribute("messageContent", "发货失败，原因：用户还未付款");
            return  "forward:/orderIndex";
        }else if (order.getState().equals("已付款")){
            model.addAttribute("messageTitle", "提示");
            model.addAttribute("messageContent", "发货成功！");
            //接下来就是改数据库里的发货状态
            order.setSendOut("已发货");
            UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("orderId",orderid);
            int rows = ordersMapper.update(order,updateWrapper);
            System.out.println("in sendOutButton , the Edited rows number is: "+rows);
            session.setAttribute("msg","修改成功");
            return "forward:/orderIndex";
        }else if (order.getState().equals("已完成")){
            model.addAttribute("messageTitle", "提示");
            model.addAttribute("messageContent", "发货失败，原因：订单已完成");
            return  "forward:/orderIndex";
        }
        return "forward:/orderIndex";
    }

    @RequestMapping("/searchOrder")
    public String searchItem(
            @RequestParam("keyword") String keyword,
            Model model){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        System.out.println(keyword);
        queryWrapper.like("orderId",keyword).
                or().like("userid",keyword).
                or().like("orderDate",keyword).
                or().like("shipaddr1",keyword).
                or().like("state",keyword).
                or().like("sendOut",keyword);

        List<Order> orderList=ordersMapper.selectList(queryWrapper);
        model.addAttribute("orderList" ,orderList);
        return "orderManage/orderIndex";
    }

    @GetMapping("/orderSearchAjax")
    @ResponseBody
    public List<Order> orderSearchAjax(
            @RequestParam("keyword") String keyword,
            HttpSession session){
        System.out.println(keyword+" in OrderController");
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("orderId",keyword).
                or().like("userid",keyword).
                or().like("orderDate",keyword).
                or().like("shipaddr1",keyword).
                or().like("state",keyword).
                or().like("sendOut",keyword);
        return ordersMapper.selectList(queryWrapper);
    }
}
